package com.course.server.service;

import com.course.server.domain.${Domain};
import com.course.server.domain.${Domain}Example;
import com.course.server.dto.${Domain}DTO;
import com.course.server.dto.PageDTO;
import com.course.server.mapper.${Domain}Mapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ${Domain}Service {

    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    public void list(PageDTO pageDTO){

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        //分页规则：调用startPage方法后，下面遇到的第一条select语句会进行分页
        ${Domain}Example ${domain}Example = new ${Domain}Example();

        <#list fieldList as field>
            <#if field.nameHump=='sort'>
        ${domain}Example.setOrderByClause("sort asc");
            </#if>
        </#list>

        List<${Domain}> ${domain}s = ${domain}Mapper.selectByExample(${domain}Example);

        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}s);

        pageDTO.setTotal(pageInfo.getTotal());

        ArrayList<${Domain}DTO> ${domain}DTOList = new ArrayList<>();

        for (int i = 0; i < ${domain}s.size(); i++) {
            ${Domain} ${domain} = ${domain}s.get(i);
            ${Domain}DTO ${domain}DTO = new ${Domain}DTO();
            BeanUtils.copyProperties(${domain}, ${domain}DTO);
            ${domain}DTOList.add(${domain}DTO);
        }
        pageDTO.setList(${domain}DTOList);
    }

    public void save(${Domain}DTO ${domain}DTO){
        ${Domain} ${domain} = CopyUtil.copy(${domain}DTO, ${Domain}.class);
        if (StringUtils.isEmpty(${domain}DTO.getId())){
            //前端没有带过来id，则是新增
            this.insert(${domain});
        }else{
            this.update(${domain});
        }
    }

    private void insert(${Domain} ${domain}){
        Date now = new Date();
        <#list fieldList as field>
            <#if field.nameHump=='createdAt'>
        ${domain}.setCreatedAt(now);
            </#if>
            <#if field.nameHump=='updatedAt'>
        ${domain}.setUpdatedAt(now);
            </#if>
        </#list>
        ${domain}.setId(UuidUtil.getShortUuid());
        ${domain}Mapper.insert(${domain});
    }

    private void update(${Domain} ${domain}){
        Date now = new Date();
        <#list fieldList as field>
            <#if field.nameHump=='updatedAt'>
        ${domain}.setUpdatedAt(now);
            </#if>
        </#list>
        ${domain}Mapper.updateByPrimaryKey(${domain});
    }

    public void delete(String id){
        ${domain}Mapper.deleteByPrimaryKey(id);
    }


}
